/*
 * Copyright 2019-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aot.test;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.function.Supplier;

import org.springframework.test.context.SmartContextLoader;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

/**
 * Load generated application contexts for supported test classes.
 * <p/>
 * Reflectively accesses {@value #INITIALIZER_NAME} generated by the
 * {@code TestContextAotProcessor} in the {@code spring-aot-test} module to retrieve the
 * mapping of all supported test classes.
 *
 * @author Stephane Nicoll
 * @author Sam Brannen
 */
class AotContextLoader {

	private static final String INITIALIZER_NAME = "org.springframework.aot.TestContextBootstrapInitializer";

	private final Map<String, Supplier<SmartContextLoader>> contextLoaders;

	AotContextLoader(Map<String, Supplier<SmartContextLoader>> contextLoaders) {
		this.contextLoaders = contextLoaders;
	}

	AotContextLoader(String initializerClassName) {
		this(loadContextLoadersMapping(initializerClassName));
	}

	AotContextLoader() {
		this(INITIALIZER_NAME);
	}

	@SuppressWarnings("unchecked")
	private static Map<String, Supplier<SmartContextLoader>> loadContextLoadersMapping(String initializerClassName) {
		try {
			Class<?> type = ClassUtils.forName(initializerClassName, null);
			Method method = ReflectionUtils.findMethod(type, "getContextLoaders");
			if (method == null) {
				throw new IllegalStateException("No getContextLoaders() method found on " + type.getName());
			}
			return (Map<String, Supplier<SmartContextLoader>>) ReflectionUtils.invokeMethod(method, null);
		}
		catch (IllegalStateException ex) {
			throw ex;
		}
		catch (Exception ex) {
			throw new IllegalStateException("Failed to load context loaders mapping", ex);
		}
	}

	SmartContextLoader getContextLoader(Class<?> testClass) {
		Supplier<SmartContextLoader> supplier = this.contextLoaders.get(testClass.getName());
		return (supplier != null) ? supplier.get() : null;
	}

	boolean isSupportedTestClass(Class<?> testClass) {
		return this.contextLoaders.containsKey(testClass.getName());
	}

}
